package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Timer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: DishServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author: 葛龙
 * @Create 2025/2/18 10:18
 * @Version 1.0
 */
@Service //注解加在实现类上面
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     */
    @Transactional //事务
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        final Dish dish = new Dish();
        //拷贝对象属性值
        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表插入1条数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        final Long id = dish.getId();

        //向口味表插入n条数据
        final List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {//说明用户提交了口味数据
            flavors.forEach(flavor -> { //flavor是遍历出的每一项
                flavor.setDishId(id);//flavors集合的元素（DishFlavor对象）只有name和value 没有id 所以
                //要对这个对象的id进行赋值

            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());//开始分页
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        //将查询得到的page封装成PageResult对象
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 根据菜品集合，删除菜品以及对应的口味表
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除？ == 是否存在正在销售的菜品？
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id); //根据用户端请求的id查询菜品
            if (dish.getStatus() == StatusConstant.ENABLE) { //说明菜品正在起售中，不能被删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //当前菜品被套餐关联不能删除
        final List<Long> setmealIdsByDishId = setmealDishMapper.getSetmealIdsByDishId(ids);
        if (setmealIdsByDishId != null && setmealIdsByDishId.size() > 0) {//说明需要删除的菜品被套餐关联不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

       /* for (Long id : ids) { //缺点：要执行多次SQL语句，性能比较低

            //删除菜品表中的菜品数据
            dishMapper.deleteById(id);

            //删除菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        }*/
        //优化：使用动态SQL，遍历集合获取id，跟上面对比，只需要执行两次SQL语句，性能会的到提升

        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);

    }

    /**
     * 根据Id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据ID查询菜品（Dish表）
        Dish dish = dishMapper.getById(id);
        //根据菜品ID（dish_id）查询口味表
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装成DishVo对象返回
        final DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品以及对应的口味数据
     *
     * @param dishDTO
     */
    @Override
    @AutoFill(value = OperationType.UPDATE)
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改菜品表基本信息
        final Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId()); //根据菜品Id删除口味数据

        //重新插入口味数据
        final List<DishFlavor> flavors = dishDTO.getFlavors();
        final Long id = dishDTO.getId();
        if (flavors != null && flavors.size() > 0) {//说明用户提交了口味数据
            flavors.forEach(flavor -> { //flavor是遍历出的每一项
                flavor.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> list = dishMapper.list(dish);
        return list;
    }

    /**
     * 设置菜品的停售起售状态
     * @param status
     * @param id
     */
    @Override
    public void setDishStatus(Integer status, Long id) {
        dishMapper.setDishStatus(status, id);
    }

}
